//
//  CXHTopOnBannerAdapter.m
//  CXHAdSDK-TopOn
//
//  Created by 陈坤 on 2024/10/10.
//

#import "CXHTopOnBannerAdapter.h"
#import "CXHTopOnBannerEvent.h"
#import "CXHTopOnCommonBiddingManager.h"
#import "CXHTopOnCommonBiddingRequest.h"
#if __has_include(<AnyThinkSDK/AnyThinkSDK.h>)
#import <AnyThinkSDK/AnyThinkSDK.h>
#else
#import "AnyThinkSDK.h"
#endif
#import <CXHAdSDK-Core/CXHAdSDK.h>
#import <CXHAdSDK-Core/CXHAdSDKBannerAdView.h>
#import <CXHAdSDK-Kit/CXHUtilsKit.h>

@interface CXHTopOnBannerAdapter ()<CXHSDKBannerAdViewDelegate>

@property(nonatomic, strong) CXHTopOnBannerEvent *customEvent;

@property (nonatomic, strong) CXHAdSDKBannerAdView *bannerView;

@property (nonatomic, assign) BOOL isC2SBinding;

@end

@implementation CXHTopOnBannerAdapter

#pragma mark - Ad load
- (void)loadADWithArgument:(ATAdMediationArgument *)argument {
    dispatch_async(dispatch_get_main_queue(), ^{
 
        CGSize bannerSize = CGSizeMake(320, 50);
        if (!CGSizeEqualToSize(argument.bannerSize, CGSizeZero)) {
            bannerSize = argument.bannerSize;
        }
        self.bannerView = [[CXHAdSDKBannerAdView alloc] initWithFrame:CGRectMake(0, 0, bannerSize.width, bannerSize.height)];
        self.bannerView.delegate = self;
        self.bannerView.posId = argument.serverContentDic[@"posid"];
        self.bannerView.controller = argument.viewController;
        [self.bannerView loadAndShow];
    });
}

#pragma mark - C2S Win Loss
- (void)didReceiveBidResult:(ATBidWinLossResult *)result {
    if (result.bidResultType == ATBidWinLossResultTypeWin) {
        [self.bannerView sendWinNotice:[result.winPrice integerValue]];
        return;
    }
    [self.bannerView sendLossNotice:[result.secondPrice integerValue]];
}

#pragma mark - CXHSDKBannerAdViewDelegate
/**
 广告获取成功
 
 @param bannerView banner实例
 */
- (void)CXH_bannerViewDidReceived:(CXHAdSDKBannerAdView *)bannerView{
    NSDictionary * extraDic = [CXHTopOnCommonAdapter getC2SInfo:[self.bannerView getBidPrice]];
    [self.adStatusBridge atOnBannerAdLoadedWithView:bannerView adExtra:extraDic];
}

/**
 广告拉取失败
 
 @param bannerView banner实例
 @param error 错误描述
 */
- (void)CXH_bannerViewFailToReceived:(CXHAdSDKBannerAdView *)bannerView error:(NSError *)error{
    [self.adStatusBridge atOnAdLoadFailed:error adExtra:nil];
}

/**
 广告点击
 
 @param bannerView 广告实例
 @param loadingPageURL 广告落地页地址，当渠道为bwt，并且customLoadingPage为YES时有值
 */
- (void)CXH_bannerViewClicked:(CXHAdSDKBannerAdView *)bannerView loadingPageURL:(NSString *)loadingPageURL{
    [self.adStatusBridge atOnAdClick:nil];
}

/**
 广告点击上报
 
 @param bannerView 广告实例
 */
- (void)CXH_bannerViewClickedReport:(CXHAdSDKBannerAdView *)bannerView{
    
}

/**
 广告关闭
 
 @param bannerView 广告实例
 */
- (void)CXH_bannerViewClose:(CXHAdSDKBannerAdView *)bannerView{
    [self.adStatusBridge atOnAdClosed:nil];
    
//    [[CXHTopOnCommonBiddingManager sharedInstance] removeRequestItemWithUnitID:self.UUID];
}

/**
 广告展示
 
 @param bannerView 广告实例
 */
- (void)CXH_bannerViewExposure:(CXHAdSDKBannerAdView *)bannerView{
    [self.adStatusBridge atOnAdShow:nil];
}

/**
 广告展示上报
 
 @param bannerView 广告实例
 */
- (void)CXH_bannerViewExposureReport:(CXHAdSDKBannerAdView *)bannerView{
    
}

/**
 关闭落地页
 
 @param bannerView 广告实例
 */
- (void)CXH_bannerAdCloseLandingPage:(CXHAdSDKBannerAdView *)bannerView{
    [self.adStatusBridge atOnAdDetailClosed:nil];
}

//- (nonnull instancetype)initWithNetworkCustomInfo:(nonnull NSDictionary *)serverInfo localInfo:(nonnull NSDictionary *)localInfo {
//    self = [super init];
//    if (self != nil) {
//        NSString *domain = [serverInfo CXH_objectOrNilForKey:@"domain"];
//        NSString *appid = [serverInfo CXH_objectOrNilForKey:@"appid"];
//        if (!kCXHStringIsEmpty(appid)) {
//            [CXHAdSDK initWithAppId:appid requestDomain:domain completionBlock:^(NSError * _Nullable error) {
//                if (error) {
//                    NSLog(@"CXHSDK 初始化失败%@",error);
//                }
//            }];
//        }
//    }
//    return self;
//}
//
//- (void)loadADWithInfo:(nonnull NSDictionary *)serverInfo localInfo:(nonnull NSDictionary *)localInfo completion:(nonnull void (^)(NSArray<NSDictionary *> * _Nonnull, NSError * _Nonnull))completion {
//    
////    NSString *posid = serverInfo[@"posid"];
//    NSString *requestUUID = serverInfo[@"tracking_info_request_id"];
//    
//    NSString *bidId = serverInfo[kATAdapterCustomInfoBuyeruIdKey];
//    if (bidId) {
//        CXHTopOnCommonBiddingRequest *request = [[CXHTopOnCommonBiddingManager sharedInstance] getRequestItemWithUnitID:requestUUID];
//        
//        if (request) {
//            self.customEvent = (CXHTopOnBannerEvent *)request.customEvent;
//            self.customEvent.requestCompletionBlock = completion;
//            self.bannerView = request.customObject;
//                   
//            [self.customEvent trackBannerAdLoaded:self.bannerView adExtra:@{}];
//        }
//        [[CXHTopOnCommonBiddingManager sharedInstance] removeRequestItemWithUnitID:requestUUID];
//        return;
//    }
//    
//    NSDictionary *extraInfo = localInfo;
//    CGSize adSize = [extraInfo[kATAdLoadingExtraBannerAdSizeKey] respondsToSelector:@selector(CGSizeValue)] ? [extraInfo[kATAdLoadingExtraBannerAdSizeKey] CGSizeValue] : CGSizeMake(320.0f, 50.0f);
//    
//    dispatch_async(dispatch_get_main_queue(), ^{
//        self.customEvent = [[CXHTopOnBannerEvent alloc] initWithInfo:serverInfo localInfo:localInfo];
//        self.customEvent.requestCompletionBlock = completion;
//        self.customEvent.UUID = requestUUID;
//
//        self.bannerView = [[CXHAdSDKBannerAdView alloc] initWithFrame:CGRectMake(0, 0, adSize.width, adSize.height)];
//        self.bannerView.delegate = self.customEvent;
//        self.bannerView.posId = serverInfo[@"posid"];
//        UIViewController *controller = localInfo[@"cxh_controller"];
//        self.bannerView.controller = controller;
//        [self.bannerView loadAndShow];
//    });
//}
//
//+ (BOOL)adReadyWithCustomObject:(nonnull id)customObject info:(nonnull NSDictionary *)info {
//    return YES;
//}
//
//+ (BOOL)isSupportAdType:(ATUnitGroupModel *)unitGroupModel{
//    return YES;
//}
//
//#pragma mark - AlexC2SBiddingRequestProtocol
//+ (void)bidRequestWithPlacementModel:(nonnull ATPlacementModel *)placementModel unitGroupModel:(nonnull ATUnitGroupModel *)unitGroupModel info:(nonnull NSDictionary *)info completion:(nonnull void (^)(ATBidInfo * _Nonnull, NSError * _Nonnull))completion {
//
//    NSString *domain = [info CXH_objectOrNilForKey:@"domain"];
//    NSString *appid = [info CXH_objectOrNilForKey:@"appid"];
//    [CXHTopOnBannerAdapter initCXHSDKWith:appid domain:domain completion:^{}];
//    
//    NSString *requestUUID = info[@"tracking_info_request_id"];
//    CXHTopOnBannerEvent *customEvent = [[CXHTopOnBannerEvent alloc]initWithInfo:info localInfo:info];
//    customEvent.isC2SBiding = YES;
//    customEvent.UUID = requestUUID;
//    
//    CXHTopOnCommonBiddingRequest * req = [CXHTopOnCommonBiddingRequest new];
//    req.customEvent = customEvent;
//    req.unitGroup = unitGroupModel;
//    req.placementID = placementModel.placementID;
//    req.bidCompletion = completion;
//    req.unitID = unitGroupModel.content[@"posid"];
//    req.extraInfo = info;
//    req.adType = CXHAdFormatBanner;
//    req.UUID = requestUUID;
//    
//    [[CXHTopOnCommonBiddingManager sharedInstance] startWithRequestItem:req];
//    NSLog(@"------> menta start bidding %@, customevent %@", requestUUID, customEvent);
//}
//
////// 返回广告位比价胜利时，第二的价格的回调，可在该回调中向三方平台返回竞胜价格  secondPrice：美元(USD)
//+ (void) sendWinnerNotifyWithCustomObject:(id)customObject secondPrice:(NSString*)price userInfo:(NSDictionary<NSString *, NSString *> *)userInfo {
//    NSLog(@"------> menta banner ad win");
//    if ([customObject isKindOfClass:CXHAdSDKBannerAdView.class]) {
//        CXHAdSDKBannerAdView *bannerView = (CXHAdSDKBannerAdView *)customObject;
//        [bannerView sendWinNotice:[price integerValue]];
//    }
//}
//
////// 返回广告位比价输了的回调，可在该回调中向三方平台返回竞败价格 winPrice：美元(USD)
//+ (void)sendLossNotifyWithCustomObject:(nonnull id)customObject lossType:(ATBiddingLossType)lossType winPrice:(nonnull NSString *)price userInfo:(NSDictionary *)userInfo {
//    NSLog(@"------> menta banner ad loss");
//    if ([customObject isKindOfClass:CXHAdSDKBannerAdView.class]) {
//        CXHAdSDKBannerAdView *bannerView = (CXHAdSDKBannerAdView *)customObject;
//        [bannerView sendLossNotice:[price integerValue]];
//    }
//}
//
//#pragma mark - private method
//
//+ (void)initCXHSDKWith:(NSString*)appid domain:(NSString *)domain completion:(void (^)(void))completion {
//    NSLog(@"====== start init cxh sdk");
//    [CXHAdSDK initWithAppId:appid requestDomain:domain completionBlock:^(NSError * _Nullable error) {
//        if (!error && completion != nil) {
//            completion();
//        }
//    }];
//}

- (void)dealloc
{
    NSLog(@"======= %s", __FUNCTION__);
}

@end
